<template>
  <div>
    <Select v-model="internalValue" class="form-item--width" clearable @on-change="handleTimeTypeChange">
      <Option v-for="(it, i) of dateOptions" :key="i" :value="it.key">{{ it.value }}</Option>
    </Select>

    <DatePicker
      v-show="value === '自定义'"
      type="daterange"
      ref="daterange_ref"
      placeholder="请选择"
      style="width: 210px"
      :options="datePickerOptions"
      @on-change="handleTimeRange"
    ></DatePicker>
  </div>
</template>

<script>
let RangeDatePickerPanel = null
import { dateYearsGap } from '@/utils/date.js'
export default {
  name: 'TimeRange',

  model: {
    prop: 'value',
    event: 'change',
  },

  props: {
    value: String,
  },

  computed: {
    internalValue: {
      get() {
        return this.value
      },

      set(v) {
        this.$emit('change', v)
      },
    },

    datePickerOptions() {
      return {
        disabledDate: (currentDate) => {
          if (!RangeDatePickerPanel) return false
          const startDate = RangeDatePickerPanel.rangeState.from
          const gapyears = Math.abs(dateYearsGap(startDate, currentDate))
          if (Number.isNaN(gapyears)) {
            return false
          }
          return Boolean(gapyears)
        },
      }
    },
  },

  methods: {
    handleTimeRange(date) {
      this.$emit('on-date-range-change', date)
    },

    handleTimeTypeChange(v) {
      this.$emit('on-time-type-change', v)
    },
  },

  mounted() {
    const daterange_ref = this.$refs['daterange_ref']
    RangeDatePickerPanel = daterange_ref.$children[1].$children[0]
  },
}
</script>

<style lang="less" scoped></style>
